// -----------------------------------------------------------------------
//  <copyright file="GlobalExceptionMiddleware.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2024 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2024-04-10 1:56</last-date>
// -----------------------------------------------------------------------

using DaprPlus.AspNetCore.Extensions;
using DaprPlus.Domain;
using DaprPlus.Properties;

using OSharp.Exceptions;


namespace DaprPlus.AspNetCore.Middleware;

public class GlobalExceptionMiddleware(RequestDelegate next, ILoggerFactory loggerFactory) : MiddlewareBase(next)
{
    private readonly ILogger _logger = loggerFactory.CreateLogger<GlobalExceptionMiddleware>();
    private readonly RequestDelegate _next = next;

    /// <summary>
    /// 执行中间件拦截逻辑
    /// </summary>
    /// <param name="context">Http上下文</param>
    /// <returns></returns>
    public override async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception exception)
        {
            if (!exception.Data.Contains("Logged"))
            {
                _logger.LogError(exception, ResDaprPlus.Format_Global_Ex, exception.Message);
            }
            var isJson = context.Request.IsJsonContextType() || context.Request.IsAjaxRequest() || context.Response.IsJsonResponse();
            if (!isJson)
            {
                throw;
            }

            if (context.Response.HasStarted)
            {
                return;
            }

            context.Response.Clear();
            context.Response.StatusCode = 200;
            context.Response.ContentType = "application/json";
            var errorMessage = exception.FormatMessage(true);
            var result = new ApiResult(errorMessage, ApiResultType.Error);
            await context.Response.WriteAsync(result.ToTextJson() ?? string.Empty);
        }
    }
}
